package com.koron.css2.systemManage.service;

import com.github.pagehelper.PageInfo;
import com.google.common.base.Objects;
import com.google.gson.Gson;
import com.koron.common.bean.query.OperationQueryBean;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.serviceManage.utils.RedisUtils;
import com.koron.css2.systemManage.bean.OperateBean;
import com.koron.css2.systemManage.bean.OperationTreeBean;
import com.koron.css2.systemManage.bean.OrgOperationBean;
import com.koron.css2.systemManage.mapper.OrgOperationMapper;
import com.koron.util.Tools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.SqlTask;
import org.springframework.stereotype.Service;
import org.swan.PingYin;

import java.util.*;

@Service
public class NewOperationService implements IOperationService{
	
	private static Logger log = LogManager.getLogger(NewOperationService.class);

	@Override
	public void addOperation(OperateBean operation) {
		
	}

	@Override
	public void addOrgOperation(String app, String orgCode, List<String> operationCodes) {
		if(StringUtils.isEmpty(orgCode)) {
			throw new IllegalArgumentException("orgCode 不能为空");
		}
		if(operationCodes == null || operationCodes.size() == 0) {
			throw new IllegalArgumentException("operationCodes 不能为空");
		}
		ADOConnection.runTask(new SqlTask() {
			@Override
			public Object run(SessionFactory factory) {
				OrgOperationMapper mapper = factory.getMapper(OrgOperationMapper.class);
				mapper.deleteByOrgCode(orgCode);
				for(String operationCode : operationCodes) {
					OrgOperationBean orgOperation = new OrgOperationBean();
					orgOperation.setId(Tools.getObjectId());
					orgOperation.setOrgCode(orgCode);
					orgOperation.setOperationCode(operationCode);
					mapper.addOrgOperation(orgOperation);
				}
				return null;
			}
		},  Void.class);
	}

	public void addOrgOperation(String app, List<String> orgCodeList, List<String> operationCodeList){
		if(orgCodeList == null || orgCodeList.size() == 0) {
			throw new IllegalArgumentException("orgCodeList 不能为空");
		}
		if(operationCodeList == null || operationCodeList.size() == 0) {
			throw new IllegalArgumentException("operationCodeList 不能为空");
		}
		ADOConnection.runTask(new SqlTask() {
			@Override
			public Object run(SessionFactory factory) {
				OrgOperationMapper mapper = factory.getMapper(OrgOperationMapper.class);
				for (String orgCode : orgCodeList){
					for(String operationCode : operationCodeList) {
						OrgOperationBean orgOperation = new OrgOperationBean();
						orgOperation.setId(Tools.getObjectId());
						orgOperation.setOrgCode(orgCode);
						orgOperation.setOperationCode(operationCode);
						mapper.deleteByOrgCodeAndOperationCode(orgCode, operationCode);
						mapper.addOrgOperation(orgOperation);
					}
				}
				return null;
			}
		},  Void.class);
	}

	@Override
	public void updateOperation(OperateBean operation) {
		
	}

	@Override
	public void deleteOperation(List<String> opCodeList) {
		
	}

	@Override
	public void addRoleOperation(String roleCode, List<String> opCodeList) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		if(opCodeList == null) {
			opCodeList = new ArrayList<>();
		}
		Map<String, String> param = new HashMap<String, String>();
		param.put("roleCode", roleCode);
		param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
		param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
		param.put("appVersionCode", ApplicationConfig.getAppVersionCode());
		String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/ops/linkRoleOps.htm";
		String result = HttpUtils.sendPostQueryAndJson(url, param, JsonUtils.objectToJson(opCodeList));
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加用户角色失败");
		}
	}

	@Override
	public List<OperateBean> getUserOPList(String userCode) {
		if(StringUtils.isEmpty(userCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		Map<String, String> param = new HashMap<String, String>();
		param.put("userCode", userCode);
		param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
		param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
		param.put("versionCode", ApplicationConfig.getAppVersionCode());
		String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/user/listPermission.htm";
		String result = HttpUtils.sendPostForm(url, param);
		JSONObject json = JSONObject.fromObject(result);
		System.out.println(json);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询用户的菜单权限失败");
		}
		List<OperateBean> operations = new ArrayList<OperateBean>();
		JSONArray array = json.getJSONArray("data");
		for(int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			OperateBean operation = new OperateBean();
			operation.setApp(ApplicationConfig.getAuthorityAppCode());
			operation.setForeignkey(object.getString("parentCode"));
			operation.setOpCode(object.getString("code"));
			operation.setOpFlag(object.getInt("type"));
			operation.setOpName(object.getString("name"));
			operation.setOpStatus(object.getInt("status"));
			operation.setOpWeight(object.getInt("sort"));
			operation.setUrl(object.getString("url"));
			operation.setIcon(object.getString("logoUrl"));
			operation.setSymbol(PingYin.getInstance().getSelling(object.getString("name"), true, ""));
			operations.add(operation);
		}
		return operations;
	}

	@Override
	public void deleteRoleOP(String roleCode, List<String> opCodeList) {
		
	}

	@Override
	public PageInfo<OperationTreeBean> listAllOperation(OperationQueryBean query) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
		param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
		param.put("versionCode", ApplicationConfig.getAppVersionCode());
		param.put("pageSize", query.getPageCount() + "");
		param.put("offset", query.getPage() + "");
		String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/app/listOperation.htm";
		String result = HttpUtils.sendPostForm(url, param);
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询应用下的所有菜单列表失败");
		}
		List<OperationTreeBean> operations = new ArrayList<OperationTreeBean>();
		JSONObject jsonObject = json.getJSONObject("data");
		JSONArray array = jsonObject.getJSONArray("data");
		for(int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			OperationTreeBean operation = new OperationTreeBean();
			operation.setParentOpCode(object.getString("parentCode"));
			operation.setOpCode(object.getString("code"));
			operation.setOpFlag(object.getInt("type"));
			operation.setId(object.getInt("id"));
			operation.setOpName(object.getString("name"));
			operation.setOpStatus(object.getInt("status"));
			operation.setOpWeight(object.getInt("sort"));
			operation.setUrl(object.getString("url"));
			operation.setIcon(object.getString("logoUrl"));
			operation.setSymbol(PingYin.getInstance().getSelling(object.getString("name"), true, ""));
			operations.add(operation);
		}
		PageInfo<OperationTreeBean> page = new PageInfo<OperationTreeBean>();
		page.setList(operations);
		page.setPageSize(query.getPageCount());
		page.setPageNum(jsonObject.getInt("totalPage"));
		page.setTotal(jsonObject.getLong("totalNumber"));
		return page;
	}

	@Override
	public List<OperationTreeBean> listOPByOrg(String app, String orgCode) {
		@SuppressWarnings("unchecked")
		List<OrgOperationBean> orgOperationList = ADOConnection.runTask(new SqlTask() {
			@Override
			public List<OrgOperationBean> run(SessionFactory factory) {
				OrgOperationMapper mapper = factory.getMapper(OrgOperationMapper.class);
				return mapper.selectByOrgCode(orgCode);
			}
		}, List.class);
		List<OperationTreeBean> data = new ArrayList<OperationTreeBean>();
		for(OrgOperationBean orgOperation : orgOperationList) {
			data.add(new OperationTreeBean(orgOperation.getOperationCode()));
		}
		return data;
	}

	@Override
	public List<OperationTreeBean> listOPByOrg(String app, UserInfoBean userInfo, String orgCode, boolean checked) {
		if(StringUtils.isEmpty(app)) {
			throw new IllegalArgumentException("app 不能为空");
		}
		if(StringUtils.isEmpty(orgCode)) {
			throw new IllegalArgumentException("orgCode 不能为空");
		}
		List<OperationTreeBean> allOperation = null;
		List<OperationTreeBean> roleOperation = listOPByOrg(app, orgCode);
		if(!checked) {
			return roleOperation;
		}
		String cache = RedisUtils.get("alloperation");
		if(StringUtils.isNotBlank(cache)) {
			allOperation = JsonUtils.jsonToList(cache, OperationTreeBean.class);
		} else {
			OperationQueryBean query = new OperationQueryBean();
			query.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
			query.setApp(app);
			query.setPage(1);
			query.setPageCount(Integer.MAX_VALUE);
			PageInfo<OperationTreeBean> page = listAllOperation(query);
			allOperation = page.getList();
			RedisUtils.setEx("alloperation", ApplicationConfig.getExpireTime(), JsonUtils.objectToJson(allOperation));
		}
		for(OperationTreeBean operation : allOperation) {
			for(OperationTreeBean op : roleOperation) {
				if(Objects.equal(operation.getOpCode(), op.getOpCode())) {
					operation.setChecked(true);
				}
				List<OperationTreeBean> btnList = operation.getBtnList();
				if(btnList != null && btnList.size() > 0) {
					for(OperationTreeBean btn : btnList) {
						if(Objects.equal(btn.getOpCode(), op.getOpCode())) {
							btn.setChecked(true);
						}
					}
				}
			}
		}
		return allOperation;
	}

	@Override
	public List<OperationTreeBean> listOPByRole(String app, UserInfoBean userInfo, String roleCode, boolean checked) {
		if(StringUtils.isEmpty(roleCode)) {
			throw new IllegalArgumentException("roleCode 不能为空");
		}
		List<OperationTreeBean> allOperation = null;
		List<OperationTreeBean> roleOperation = listOPByRole(app, roleCode);
		if(StringUtils.isNotEmpty(userInfo.getCurWaterCode())) {
			allOperation = listOPByOrg(app, userInfo.getCurWaterCode());
			Iterator<OperationTreeBean> iterator = roleOperation.iterator();
			while (iterator.hasNext()) {
				OperationTreeBean operation = iterator.next();
				if(!allOperation.contains(operation)) {
					iterator.remove();
				}
			}
		}
		if(!checked) {
			return roleOperation;
		}
		//运维上水司编号为空获取角色所有权限（无关水司）
		if(StringUtils.isEmpty(userInfo.getCurWaterCode())){
			OperationQueryBean query = new OperationQueryBean();
			query.setTenantCode(ApplicationConfig.getAuthorityTenantCode());
			query.setApp(app);
			query.setPage(1);
			query.setPageCount(Integer.MAX_VALUE);
			PageInfo<OperationTreeBean> page = listAllOperation(query);
			allOperation = page.getList();
		}
		for(OperationTreeBean operation : allOperation) {
			for(OperationTreeBean op : roleOperation) {
				if(Objects.equal(operation.getOpCode(), op.getOpCode())) {
					operation.setChecked(true);
				}
				List<OperationTreeBean> btnList = operation.getBtnList();
				if(btnList != null && btnList.size() > 0) {
					for(OperationTreeBean btn : btnList) {
						if(Objects.equal(btn.getOpCode(), op.getOpCode())) {
							btn.setChecked(true);
						}
					}
				}
			}
		}
		return allOperation;
	}
	
	private List<OperationTreeBean> listOPByRole(String app, String roleCode) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
		param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
		param.put("versionCode", ApplicationConfig.getAppVersionCode());
		param.put("roleCode", roleCode);
		String url = ApplicationConfig.getAuthorityNewUrl() + "/port/2.0/ops/listRoleOps.htm";
		String result = HttpUtils.sendPostForm(url, param);
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("查询应用下的所有菜单列表失败");
		}
		List<OperationTreeBean> operations = new ArrayList<OperationTreeBean>();
		JSONArray array = json.getJSONArray("data");
		for(int i = 0; i < array.size(); i++) {
			JSONObject object = array.getJSONObject(i);
			OperationTreeBean operation = new OperationTreeBean();
			operation.setParentOpCode(object.getString("parentCode"));
			operation.setOpCode(object.getString("code"));
			operation.setOpFlag(object.getInt("type"));
			operation.setOpName(object.getString("name"));
			operation.setOpStatus(object.getInt("status"));
			operation.setOpWeight(object.getInt("sort"));
			operation.setUrl(object.getString("url"));
			operation.setId(object.getInt("id"));
			operation.setIcon(object.getString("logoUrl"));
			operation.setSymbol(PingYin.getInstance().getSelling(object.getString("name"), true, ""));
			operations.add(operation);
		}
		return operations;
	} 
	
	public static void main(String[] args) {
		IOperationService operationService = new OperationService();
		// operationService.listAllOperation(query);
		/*List<OperateBean> data = operationService.getUserOPList("zxy");
		System.out.println(new Gson().toJson(data));*/
		// operationService.addRoleOperation("0fdd73a0-ff2d-4a35-9c76-79c2795c24c3", Arrays.asList("08747e134601423d979daef1294f18ca", "60a28fae7a4147cc97e17ff7e13fcc2b"));
		/*List<OperationTreeBean> data = operationService.listOPByRole("", "0fdd73a0-ff2d-4a35-9c76-79c2795c24c3");
		System.out.println(new Gson().toJson(data));*/
		OperationQueryBean query = new OperationQueryBean();
		query.setPage(1);
		query.setPageCount(300);
		PageInfo<OperationTreeBean> data = operationService.listAllOperation(query);
		System.out.println(new Gson().toJson(data.getList()));
	}
	
	public void addOperation(OperationTreeBean operation) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("accessAppCode", "f6b7fb23-eb14-487d-8658-ab9080a2e5dc");
		param.put("accessAppSecret", "123456");
		param.put("appVersion", "f9526844-e669-482a-8296-5feb2272bac8");
		param.put("parent", Objects.equal(operation.getParentOpCode(), "01") ? "" : operation.getParentOpCode());
		param.put("name", operation.getOpName());
		param.put("code", operation.getOpCode());
		param.put("type", "1");
		param.put("appCode", "f6b7fb23-eb14-487d-8658-ab9080a2e5dc");
		param.put("logoUrl", StringUtils.defaultString(operation.getIcon(), ""));
		param.put("url", operation.getUrl());
		String url = "http://uma.yinchuanwater.com:9001/port/2.0/app/operation/add.htm";
		String result = HttpUtils.sendPostForm(url, param);
		JSONObject json = JSONObject.fromObject(result);
		if(json.getInt("code") != 0) {
			log.error(json.getString("description"));
			throw new RuntimeException("添加用户角色失败");
		}
	}
}
